package cn.larry.common.blockchain;

import lombok.ToString;

import java.util.Date;

/**
 * This is created,
 * but not necessarily updated by me.
 * Therefore, AUTHOR is useless.
 * 2024/10/11 11:33
 *
 * @Version 1.0
 */
@ToString
public class Block {
    public String hash;
    public String previousHash;
    private String data;
    private long timeStamp;
    private int nonce;
    private final String APPLYSHA256_STR_HEAD = "base-java-code";// 自定义

    public Block(String data, String previousHash) {
        this.data = data;
        this.previousHash = previousHash;
        this.timeStamp = new Date().getTime();
        this.hash = calculateHash();
    }

    /**
     * 计算值
     * 【该加密方式千万不能公开】
     *
     * @return
     */
    public String calculateHash() {
        return calculateHash(APPLYSHA256_STR_HEAD + previousHash + Long.toString(timeStamp) + Integer.toString(nonce) + data);
    }

    private String calculateHash(String input) {
        return StringUtil.applySha256(input);
    }

    /**
     * 验证值
     *
     * @return
     */
    public boolean verificationHash() {
        String calculateHash = calculateHash();
        return calculateHash.equals(hash);
    }

    public void mineBlock(int difficulty) {
        String target = new String(new char[difficulty]).replace('\0', '0');
        while (!hash.substring(0, difficulty).equals(target)) {
            nonce++;
            hash = calculateHash();
        }
        System.out.println("Block Mined!!! : " + hash);
    }
}
